# -*- coding: utf-8 -*-
from match import Extractor
import regex as re
from storage.digit_util import *


def get_number(prefix, suffix, text):
    num_reg_pattern = "([亿万千百十零两一二三四五六七八九点\\.0123456789]{1,40})"
    pattern = re.compile(prefix + num_reg_pattern + suffix, re.S)
    result_list = []
    number_str_list = pattern.findall(text)
    for number_str in number_str_list:
        number_str = number_str.replace("两","二")
        if(number_str == "万"):
            continue
        cn_num = True
        arabic_num = True
        for char in number_str:
            if ord(char) > 512:
                arabic_num = False
            else:
                cn_num = False
        if arabic_num:
            try:
                result_list.append(float(number_str))
            except:
                print("bad number" + number_str)
        if cn_num:
            result_list.append(float(takeChineseNumberFromString(number_str)["replacedText"]))
        if not cn_num and not arabic_num and number_str.endswith("亿"):
            try:
                result_list.append(float(number_str[:-1]) * 100000000)
            except:
                print("bad number" + number_str)
        if not cn_num and not arabic_num and number_str.endswith("万"):
            try:
                result_list.append(float(number_str[:-1]) * 10000)
            except:
                print("bad number" + number_str)
    return result_list


class JiaoTongZhaoShiExtractor(Extractor):

    # 该辩护要点仅仅适用于盗窃
    @staticmethod
    def is_my_job(file_path):
        return "交通肇事" in file_path

    @staticmethod
    def extract(text):
        result = {}
        # 一人死亡 二人死亡 当场死亡 2人死亡 十一人死亡 十二人死亡
        death_count_list = get_number("", "人死亡", text)
        if (len(death_count_list) == 0):
            result["死亡人数"] = 0
        else:
            result["死亡人数"] = max(death_count_list)
        money_count_list = get_number("损失[^亿万千百十零两一二三四五六七八九点\\.0123456789]{0,5}", "元", text)
        if (len(money_count_list) == 0):
            result["财产损失"] = 0
        else:
            result["财产损失"] = max(money_count_list)
        alcohol_count_list = get_number("", "[^亿万千百十零一二三四五六七八九点\\.0123456789]{0,2}[mM][gG]", text)
        if (len(alcohol_count_list) == 0):
            result["血液酒精浓度"] = 0
        else:
            result["血液酒精浓度"] = max(alcohol_count_list)
        result["肇事逃逸"] = "逃逸" in text
        result["主动赔偿"] = "主动赔偿" in text or "积极赔偿" in text
        return result


if __name__ == '__main__':
    print(JiaoTongZhaoShiExtractor.extract("造成1人死亡，损失人民币5万元；承担次要责任，事后驾车逃逸，但积极赔偿损失。"))
    from match import *
    from storage import *
    import json
    import os

    data_util = DataUtil("../data/交通肇事罪")
    extractors = [JiaoTongZhaoShiExtractor]

    file_path, text = data_util.next_line()
    count_dict = {}
    count_key_list = ["死亡人数", "财产损失", "肇事逃逸", "主动赔偿", "血液酒精浓度"]
    while text:
        text_json = json.loads(text)
        if file_path not in count_dict:
            count_dict[file_path] = {"count": 0}
        for extractor in extractors:
            if extractor.is_my_job(file_path):
                result = extractor.extract("\n".join(text_json["content"]))
                for key in count_key_list:
                    result_value = result[key]
                    if(type(result_value) == int or type(result_value) == float):
                        if key in count_dict[file_path]:
                            count_dict[file_path][key] = count_dict[file_path][key] + result_value
                        else:
                            count_dict[file_path][key] = result_value
                    else:
                        if key in count_dict[file_path]:
                            if result_value in count_dict[file_path][key]:
                                count_dict[file_path][key][result_value] = count_dict[file_path][key][result_value]  + 1
                            else:
                                count_dict[file_path][key][result_value]  = 1
                        else:
                            count_dict[file_path][key] = {}
                            count_dict[file_path][key][result_value] = 1
        count_dict[file_path]["count"] = count_dict[file_path]["count"] + 1
        file_path, text = data_util.next_line()
    for key in count_dict:
        print(key)
        count = count_dict[key]["count"]
        for ckey in count_key_list:
            ckey_result = count_dict[key][ckey]
            if(type(ckey_result) == int or type(ckey_result) == float):
                print(str(ckey)+":%f"%(ckey_result/float(count)))
            else:
                for cckey in ckey_result:
                    print(str(ckey)+"_"+str(cckey)+":%f"%(ckey_result[cckey]/float(count)))
    print(count_dict)
